from sanic.views import HTTPMethodView
from sanic.response import text,json
import time
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
import json as jn
import re
from processing.Sql_DataFrom import ProJosn
import requests
from qiniu import Auth, put_data
https = 'http://s6fj703hj.hn-bkt.clouddn.com/'

access_key = 'E6V25lrPSq7LPacKPd7fKhihIQ2bco8K5x2z4Hgp'

secret_key = '0aQ4rneBSJDFDBlgdbHwb62pQH8YQDFdfNFeWnL3'

# 空间名
bucket_name = 'baibaotuju'
class upload(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        q = Auth(access_key=access_key, secret_key=secret_key)
        token = q.upload_token(bucket=bucket_name)
        file_manage_type = request.form['file_manage_type'][0]
        for i in request.files['file']:
            ret, res = put_data(token, f'image/{i[2]}', data=i[1])
            ret.get('key')
            text_body = jn.loads(res.text_body)
            sql = """
                       insert into file_manage(merchant_id,url,suffix,type,file_manage_type,other,ctime) VALUES (%s,%s,%s,%s,%s,%s,now())
                    """
            houzui = text_body['key'].split('.')[1]
            db.insert(sql, (user_id, text_body['key'], houzui, '', file_manage_type, text_body['hash']))
        data = {
            'code': 200,
            'message': '上传成功!'
        }

        return json(data)

class filemanage_group_add(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = """
                   insert into filemanage_group(merchant_id,name,type,other,ctime) VALUES (%s,%s,%s,%s,now())
                """
        db.insert(sql, (user_id, html_data['name'], html_data['type'], html_data['other']))

        data = {
            'code': 200,
            'message': '创建成功!'
        }

        return json(data)

class filemanage_group_list(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = """
                   select id,name from filemanage_group where merchant_id=%s
                """

        data = db.find_all(sql, (user_id))
        if data:
            data = ProJosn(data, sql).to_dict(orient='records')
        else:
            data = []

        data = {
            'code': 200,
            'data': data,
            'message': '请求成功!'
        }

        return json(data)

class filemanage_group_delete(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = """
                    delete from filemanage_group where id=%s
                """

        db.delete(sql, (html_data['id']))

        sql1 = "select * from filemanage_group where id=%s"
        if db.find_one(sql1, html_data['id']):
            data = {
                'code': 400,
                'message': '删除失败!'
            }
        else:
            data = {
                'code': 200,
                'message': '删除成功!'
            }

        return json(data)
class get_file_manage(HTTPMethodView):
    async def get(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        file_manage_id = (request.args.get('file_manage_id'))

        sql = f" select id,url,suffix from file_manage where merchant_id=%s"

        # 获取总数据
        tol = """ SELECT COUNT(*) FROM file_manage"""
        tol_data = db.find_one(tol)

        if file_manage_id == '0' or file_manage_id == 0:
            pass
        else:
            sql = f" select id,url,suffix from file_manage where file_manage_type={file_manage_id} and merchant_id=%s"

        # 分页pageNum
        if pageNum == 1:
            sql += f" LIMIT {pageSize} "
        else:
            sql += f" LIMIT {pageNum * pageSize - pageSize},{pageNum * pageSize} "

        data = db.find_all(sql, (user_id))

        if data:
            data = ProJosn(data, sql, 'sql').to_dict(orient='records')
        else:
            data = []

        data = {
            'code': 200,
            'data': data,
            'tol_data': tol_data[0],
            'message': '请求成功!'
        }

        return json(data)
class ImageDel(HTTPMethodView):
    async def post(self, request):
        # 登录用户的id
        user_id = request.app.ctx.user_id
        db = request.app.ctx.db

        html_data = request.json

        sql = f" delete from file_manage where"

        sum = 0
        for i in html_data['ids'].split(','):
            if sum == 0:
                sql += f" id={int(i)} "
            else:
                sql += f" or id={int(i)} "
            sum += 1

        db.delete(sql)

        data = {
            'code': 200,
            'message': '删除成功!'
        }
        return json(data)